package com.ittx.dzt.baidu.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import com.ittx.dzt.baidu.constant.BaiduApiConstant;
import com.ittx.dzt.baidu.handler.AbstractBaiduByTimeApiHandler;
import com.ittx.dzt.edi.constant.GeneralConstant;
import com.ittx.dzt.edi.constant.PlatformMessageConstant;
import com.ittx.dzt.edi.dto.PlatformApiParamDTO;
import com.ittx.dzt.edi.dto.StoreConfigDTO;
import com.ittx.dzt.edi.dto.TimeFrameDTO;
import com.ittx.dzt.edi.vo.ResponseMessageVO;
import com.ittx.dzt.sys.response.Result;
import lombok.extern.slf4j.Slf4j;
import open.constant.PlatformApiConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 增量下载订单
 * <p>
 * 查询订单列表 /PlatOrderBusinessQueryService/getPartConsignOrderList
 * cy.salesOrder.download.byTimeFrame
 * https://dev2.baidu.com/content?sceneType=0&pageId=104167&nodeId=1138&subhead=
 * </p>
 *
 * @author wl_code@163.com
 * @version 1.0
 * @date 2025/2/27
 */
@Slf4j
@Service
public class BaiduSalesOrderDownloadByTimeService extends AbstractBaiduByTimeApiHandler<TimeFrameDTO> {

	private static final int DEFAULT_PAGE_SIZE = 50;

	@Autowired
	private BaiduSalesOrderDownloadByIdService baiduSalesOrderDownloadByIdService;


	@Override
	protected String getMqTopic() {
		return BaiduApiConstant.Rocket.BAIDU_DOWNLOAD_ORDER_SEARCHLIST_BY_TIME_BATCH_SPLIT_TOPIC;
	}

	@Override
	public String getBaiduMethod() {
		return "/PlatOrderBusinessQueryService/getPartConsignOrderList";
	}

	@Override
	public String getLocalApiMethod() {
		return PlatformApiConstant.InboundInterface.SALESORDER_DOWNLOAD_BY_TIMEFRAME;
	}

	@Override
	protected Result<?> doProcessByNormalType(PlatformApiParamDTO platformApiParamDTO, TimeFrameDTO timeFrameDTO) {
		//分发数据,异步下载
		Map<String, Boolean> logMap = new HashMap<>();
		return this.requestListBySdk(platformApiParamDTO, timeFrameDTO, logMap);

	}

	@Override
	protected Result<?> doProcessByCheckType(PlatformApiParamDTO platformApiParamDTO, TimeFrameDTO timeFrameDTO) {
		//探查成功时不返回完整数据,只返回数量
		return this.requestListBySdk(platformApiParamDTO, timeFrameDTO, null);
	}

	@Override
	protected Result<?> doProcessByIdType(PlatformApiParamDTO platformApiParamDTO, TimeFrameDTO timeFrameDTO) {
		String orderId = platformApiParamDTO.getPlatformIdentifierTag();
		return this.asyncHandlerById(platformApiParamDTO, orderId);
	}

	/**
	 * sdk
	 * 请求平台接口
	 */
	private Result<?> requestListBySdk(PlatformApiParamDTO platformApiParamDTO, TimeFrameDTO timeFrameDTO, Map<String, Boolean> logMap) {
		StoreConfigDTO storeConfig = platformApiParamDTO.getStoreConfig();
		try {

			Map<String, Object> extendMap = platformApiParamDTO.getExtendMap();
			String authUserName = MapUtil.getStr(extendMap, "authUserName", "");
			if (StrUtil.isEmpty(authUserName)) {
				return Result.error("授权用户名,不可为空,请在拓展参数中加入参数:{}", "authUserName");
			}
			Map<String, Object> headerMap = MapUtil.newHashMap();
			headerMap.put("accessToken", storeConfig.getSessionKey());
			headerMap.put("userName", authUserName);


			Map<String, Object> bodyMap = MapUtil.newHashMap();
			bodyMap.put("startUpdateTime", timeFrameDTO.getFrom().format(DateTimeFormatter.ofPattern(GeneralConstant.DEFAULT_DATE_TIME_PATTERN)));
			bodyMap.put("endUpdateTime", timeFrameDTO.getTo().format(DateTimeFormatter.ofPattern(GeneralConstant.DEFAULT_DATE_TIME_PATTERN)));
			// 	取值范围：枚举值，列表如下// 5 - 综合电商// 269 - 本地生活// 100012 - 招财猫
			bodyMap.put("appId", "5");
			bodyMap.put("shopId", storeConfig.getStoreUniqueCode());
			bodyMap.put("pageNum", 1);
			bodyMap.put("pageSize", DEFAULT_PAGE_SIZE);

			Map<String, Object> requestMap = MapUtil.newHashMap();
			requestMap.put("header", headerMap);
			requestMap.put("body", bodyMap);

			Result<?> result = this.executeApi(storeConfig, requestMap, platformApiParamDTO.getRequestId());
			if (result.hasError()) {
				return result;
			}
			Map respMap = (Map) result.getData();
			Map respBodyMap = MapUtil.get(respMap, "body", Map.class);
			List dataList = MapUtil.get(respBodyMap, "data", List.class);
			Map<String, Object> dataMap = Convert.toMap(String.class, Object.class, dataList.get(0));
			Integer totalCount = MapUtil.getInt(dataMap, "total");

			// 探查模式只返回总数
			if (PlatformApiConstant.ApiByTime.CHECK.equals(platformApiParamDTO.getQueryType())) {
				return Result.success().addData(totalCount);
			}
			int totalPage = this.totalPage(totalCount, DEFAULT_PAGE_SIZE);
			if (totalPage >= 1) {
				// 倒序查询，防止漏单
				for (int i = totalPage; i > 0; i--) {
					bodyMap.put("pageNum", i);
					result = this.executeApi(storeConfig, requestMap, platformApiParamDTO.getRequestId());
					if (result.hasError()) {
						return result;
					}
					respMap = (Map) result.getData();
					respBodyMap = MapUtil.get(respMap, "body", Map.class);
					dataList = MapUtil.get(respBodyMap, "data", List.class);
					dataMap = Convert.toMap(String.class, Object.class, dataList.get(0));
					List orderList = MapUtil.get(dataMap, "list", List.class);
					if (CollUtil.isNotEmpty(orderList)) {
						for (int i1 = 0; i1 < orderList.size(); i1++) {
							Map<String, Object> orderMap = Convert.toMap(String.class, Object.class, orderList.get(i1));
							String orderId = MapUtil.getStr(orderMap, "orderId");
							platformApiParamDTO.setPlatformIdentifierTag(orderId);
							sendToSplitTopic(platformApiParamDTO, orderId, logMap);
						}
					}
				}
			}
		} catch (Exception e) {
			String msg = StrUtil.format(PlatformMessageConstant.MSG_PLAT_0003_MSG, platformApiParamDTO.getRequestId(), this.getPlatformCode(), platformApiParamDTO.getApi(), e.getMessage());
			log.error(msg);
			return Result.error(new ResponseMessageVO(PlatformMessageConstant.MSG_PLAT_0003_MSG, msg));
		}
		return Result.success(logMap);
	}

	/**
	 * sdk
	 * 根据单号查询单条订单信息-- 多线程执行
	 */
	@Override
	public Result<?> asyncHandlerById(PlatformApiParamDTO platformApiParamDTO, String orderId) {
		Result<?> result = baiduSalesOrderDownloadByIdService.getOrderById(platformApiParamDTO, orderId);
		if (!result.isSuccess()) {
			return result;
		}
		return this.sendRequestToPlatform(platformApiParamDTO, result.getData(), true);
	}

	/**
	 * 参数校验
	 *
	 * @param platformApiParamDTO 平台请求参数
	 * @param timeFrameDTO        接口请求参数
	 */
	public Result<?> checkParams(PlatformApiParamDTO platformApiParamDTO, TimeFrameDTO timeFrameDTO) {
		if (timeFrameDTO == null || platformApiParamDTO.getStoreConfig() == null ||
				timeFrameDTO.getTo() == null || timeFrameDTO.getFrom() == null) {
			String msg = StrUtil.format(PlatformMessageConstant.MSG_PLAT_0004_MSG, platformApiParamDTO.getRequestId(),
					this.getPlatformCode(), getLocalApiMethod(), timeFrameDTO);
			log.error(msg);
			return Result.error(new ResponseMessageVO(PlatformMessageConstant.MSG_PLAT_0004, msg));
		}
		return Result.success();
	}


}
